package com.yikaiye.android.yikaiye.ui.activity.login;

import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;

import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yikaiye.android.yikaiye.R;
import com.yikaiye.android.yikaiye.application.MyApplication;
import com.yikaiye.android.yikaiye.base.BaseActivity;
import com.yikaiye.android.yikaiye.config.Constant;
import com.yikaiye.android.yikaiye.databinding.ActivityLoginBinding;
import com.yikaiye.android.yikaiye.model.EventBusModel;
import com.yikaiye.android.yikaiye.ui.activity.MainActivity;
import com.yikaiye.android.yikaiye.ui.activity.login.viewmodel.LoginViewModel;
import com.yikaiye.android.yikaiye.utils.JumpIntent;
import com.yikaiye.android.yikaiye.utils.ToastHelper;
import com.yikaiye.android.yikaiye.utils.sharedpreference.SPUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * 登录
 */
public class LoginActivity extends BaseActivity<ActivityLoginBinding, LoginViewModel> {

    private boolean isPassLogin;
    private boolean isShowPwd;
    private IWXAPI api;
    /**
     * 0密码、2验证码、3是app微信登录
     */
    private int loginType;

    @Override
    protected LoginViewModel bindModel() {
        return getViewModel(this, LoginViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void initData() {
        binding.setLoginViewModel(viewModel);
        api = WXAPIFactory.createWXAPI(this, Constant.WE_CHAT_APP_ID, false);
        // 暂时只显示验证码登录
        binding.tvLoginWay.setText(getString(R.string.phone_num_password_login));
        binding.rlCodeLogin.setVisibility(View.VISIBLE);
        binding.rlPassLogin.setVisibility(View.GONE);
        binding.etPassword.setText("");
        viewModel.phoneNumber.setValue(SPUtil.getString(Constant.phoneNum, ""));
    }

    @Override
    protected void initClick() {
        viewModel.onDelayClick(binding.back, o -> finish());
        viewModel.onDelayClick(binding.tvLoginWay, o -> {
            if (isPassLogin) {
                binding.tvLoginWay.setText(getString(R.string.phone_num_password_login));
                binding.rlCodeLogin.setVisibility(View.VISIBLE);
                binding.rlPassLogin.setVisibility(View.GONE);
                binding.etPassword.setText("");
            } else {
                binding.tvLoginWay.setText(getString(R.string.phone_num_code_login));
                binding.rlCodeLogin.setVisibility(View.GONE);
                binding.rlPassLogin.setVisibility(View.VISIBLE);
                binding.etCode.setText("");
            }
            isPassLogin = !isPassLogin;
        });
        viewModel.onDelayClick(binding.cdtCountdown, o -> {
            if (TextUtils.isEmpty(viewModel.phoneNumber.getValue())) {
                ToastHelper.show(getString(R.string.please_input_cell_number));
                return;
            }
            showLoadingDialog();
            viewModel.sendCode(5, viewModel.phoneNumber.getValue());
        });
        viewModel.onDelayClick(binding.tvForgetPwd, o -> JumpIntent.jump(this, FindPasswordActivity.class));
        viewModel.onDelayClick(binding.tvNewRegister, o -> JumpIntent.jump(this, RegisterActivity.class));
        viewModel.onDelayClick(binding.btnLogin, o -> {
            if (isPassLogin) {
                Constant.isLoginToken = true;
                showLoadingDialog();
                loginType = 0;
                viewModel.login(loginType, viewModel.phoneNumber.getValue(), null, viewModel.password.getValue(), null);
            } else {
                viewModel.verifyCode(viewModel.phoneNumber.getValue(), viewModel.code.getValue());
            }
        });
        viewModel.onDelayClick(binding.llWxLogin, o -> {
            if (api.isWXAppInstalled()) {
                // 原生微信授权
                SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = "none";
                api.sendReq(req);
            } else {
                ToastHelper.show(getString(R.string.please_install_wechat));
            }
        });
        viewModel.onDelayClick(binding.ivPwdStatus, o -> {
            isShowPwd = !isShowPwd;
            if (isShowPwd) {
                binding.etPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                binding.ivPwdStatus.setImageResource(R.mipmap.icon_pass_open);
            } else {
                binding.etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                binding.ivPwdStatus.setImageResource(R.mipmap.icon_pass_close);
            }
            binding.etPassword.setSelection(binding.etPassword.getText().toString().length());
        });

        // 获取验证码成功
        viewModel.codeSuccess.observe(this, verifyCodeModel -> {
            dismissLoadingDialog();
            binding.cdtCountdown.startCountDown(
                    context,
                    60,
                    getString(R.string.send_code_again),
                    "s"
            );
            ToastHelper.show(getString(R.string.code_has_been_sent));
        });
        // 获取验证码失败
        viewModel.codeError.observe(this, s -> {
            dismissLoadingDialog();
            ToastHelper.show(s);
        });

        // token验证成功
        viewModel.tokenVerifySuccess.observe(this, userModel -> {
            Constant.isLoginToken = true;
            loginType = 2;
            showLoadingDialog();
            viewModel.login(loginType, viewModel.phoneNumber.getValue(), userModel.getVerifyToken(), null, null);
        });
        // token验证失败
        viewModel.tokenVerifyError.observe(this, ToastHelper::show);

        // 登录成功
        viewModel.loginSuccess.observe(this, userModel -> {
            Constant.isLoginToken = false;
            if (loginType == 3 && !TextUtils.isEmpty(userModel.getPhone())) {
                MyApplication.manager.saveUserInfo(userModel);
                MyApplication.manager.setLogin(false);
                Bundle bundle = new Bundle();
                bundle.putString(Constant.USER_ID_KEY, userModel.getUserId());
                JumpIntent.jump(this, BindPhoneNumActivity.class, bundle);
            } else {
                Constant.isJumpToLogin = true;
                MyApplication.manager.saveUserInfo(userModel);
                SPUtil.put(Constant.phoneNum, viewModel.phoneNumber.getValue());
                JumpIntent.jump(this, MainActivity.class, true);
            }
            dismissLoadingDialog();
        });

        // 登录失败
        viewModel.loginError.observe(this, s -> {
            dismissLoadingDialog();
            ToastHelper.show(s);
        });

        viewModel.phoneNumber.observe(this, s -> changeBtnStatus());
        viewModel.code.observe(this, s -> changeBtnStatus());
        viewModel.password.observe(this, s -> changeBtnStatus());
    }

    private void changeBtnStatus() {
        if (!TextUtils.isEmpty(viewModel.phoneNumber.getValue())
                && isPassLogin
                ? !TextUtils.isEmpty(viewModel.password.getValue())
                : !TextUtils.isEmpty(viewModel.code.getValue())
        ) {
            binding.btnLogin.setEnabled(true);
            binding.btnLogin.setBackgroundResource(R.drawable.shape_f93f50_4dp);
        } else {
            binding.btnLogin.setEnabled(false);
            binding.btnLogin.setBackgroundResource(R.drawable.shape_fcebea_4dp);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(EventBusModel eventBusModel) {
        if (eventBusModel != null) {
            Constant.isLoginToken = true;
            showLoadingDialog();
            loginType = 3;
            viewModel.login(loginType, null, null, null, eventBusModel.getMessage());
        }
    }
}
